<?php

namespace app\admin\controller;

use app\common\model\Article as ArticleModel;
use app\common\model\Category as CategoryModel;
use app\common\controller\AdminBase;
use think\Db;

/**
 * 文章管理
 * Class Article
 * @package app\admin\controller
 */
class Article extends AdminBase {

    protected $article_model;
    protected $category_model;

    protected function _initialize() {
        parent::_initialize();
        $this->article_model = new ArticleModel();
        $this->category_model = new CategoryModel();

        $category_level_list = $this->category_model->getLevelList();
        $this->assign('category_level_list', $category_level_list);
    }

    /**
     * 文章管理
     * @param int    $cid     分类ID
     * @param string $keyword 关键词
     * @param int    $page
     * @return mixed
     */
    public function index($cid = 0, $keyword = '', $page = 1) {
        $map = [];
        $field = 'id,title,cid,author,reading,status,publish_time,sort';

        if ($cid > 0) {
            $category_children_ids = $this->category_model->where(['path' => ['like', "%,{$cid},%"]])->column('id');
            $category_children_ids = (!empty($category_children_ids) && is_array($category_children_ids)) ? implode(',', $category_children_ids) . ',' . $cid : $cid;
            $map['cid'] = ['IN', $category_children_ids];
        }

        if (!empty($keyword)) {
            $map['title'] = ['like', "%{$keyword}%"];
        }

        
        $article_list = $this->article_model->field($field)->where($map)->order(['publish_time' => 'DESC'])->paginate(10, false, ['query'=>['cid'=>$cid,'keyword'=>$keyword],'page' => $page]);

        $category_list = $this->category_model->column('name', 'id');

        return $this->fetch('index', ['article_list' => $article_list, 'category_list' => $category_list, 'cid' => $cid, 'keyword' => $keyword]);
    }
    
    /**
     * 医院文章管理
     * @param int    $cid     分类ID
     * @param string $keyword 关键词
     * @param int    $page
     * @return mixed
     */
    public function index2($cid = 0, $keyword = '', $page = 1) {
        $map = [];
        $field = 'id,title,cid,city,reading,publish_time,sort';

        if ($cid > 0) {
            $category_children_ids = $this->category_model->where(['path' => ['like', "%,{$cid},%"]])->column('id');
            $category_children_ids = (!empty($category_children_ids) && is_array($category_children_ids)) ? implode(',', $category_children_ids) . ',' . $cid : $cid;
            $map['cid'] = ['IN', $category_children_ids];
        }

        if (!empty($keyword)) {
            $map['title'] = ['like', "%{$keyword}%"];
        }

        $article_list = Db::name('Article2')->field($field)->where($map)->order(['publish_time' => 'DESC'])->paginate(10, false, ['query'=>['cid'=>$cid,'keyword'=>$keyword],'page' => $page]);

        $category_list = $this->category_model->column('name', 'id');

        return $this->fetch('index2', ['article_list' => $article_list, 'category_list' => $category_list, 'cid' => $cid, 'keyword' => $keyword]);
    }
    
    
    

    /**
     * 添加文章
     * @return mixed
     */
    public function add() {
        return $this->fetch();
    }

    /**
     * 保存文章
     */
    public function save() {
        if ($this->request->isPost()) {
            $data = $this->request->param();

            //如果没有上传图片 那么默认取第一张缩略图作为封面
            if(!$data['thumb']){
                $data['thumb'] = $this->thumb($data['content']);
                if(!$data['thumb']){
                    $this->error('请至少有一张封面图，如缩略图不传 默认用文章里第一张图片作为封面！');
                }
            }
            
            if ($data['labels'] && $data['pingying']) {
                $labels = explode(',', str_replace('，', ',', $data['labels']));
                
                $pingying = explode(',', str_replace('，', ',', $data['pingying']));

                if (count($labels) != count($pingying)) {
                    $this->error('标签和拼音个数不一致！');
                }
            }

            $validate_result = $this->validate($data, 'Article');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $data['publish_time'] = time();
                if ($this->article_model->allowField(true)->save($data)) {
                    //文章标签关联
                    $this->linkArticleLabel($data,$this->article_model->id);
                    
                    //文章专题关联
                    $this->linkArticleSubject($data,$this->article_model->id);
                    
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑文章
     * @param $id
     * @return mixed
     */
    public function edit($id) {
        $article = $this->article_model->find($id);

        //所有标签
        $label_list = array_reduce(Db::name('Label')->select(), function(&$newArray,$v){
            $newArray[$v['id']] = $v;
            return $newArray;
        });
       
        //获取文章对应的标签
        $article_label = Db::name('ArticleLabel')->where(['article_id' => $id])->select();
        
        $labels ='';
        $pingying ='';
        
        if($article_label){
            foreach ($article_label as $k=>$v){
                $labels .= $label_list[$v['label_id']]['label_name'].',';
                $pingying .= $label_list[$v['label_id']]['pingying'].',';
            }
        }
        
        $this->assign(array(
            'label_list' => $label_list,
            'article_label' => $article_label,
            'labels' => trim($labels,','),
            'pingying' => trim($pingying,','),
        ));
        return $this->fetch('edit', ['article' => $article]);
    }

    /**
     * 更新文章
     * @param $id
     */
    public function update($id) {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            
            //如果没有上传图片 那么默认取第一张缩略图作为封面
            if(!$data['thumb']){
                $data['thumb'] = $this->thumb($data['content']);
                if(!$data['thumb']){
                    $this->error('请至少有一张封面图，如缩略图不传 默认用文章里第一张图片作为封面！');
                }
            }
            
            if (($data['labels'] && $data['pingying'])) {
                $labels = explode(',', str_replace('，', ',', $data['labels']));
                $pingying = explode(',', str_replace('，', ',', $data['pingying']));

                if (count($labels) != count($pingying)) {
                    $this->error('标签和拼音个数不一致！');
                }
            }
            
            $validate_result = $this->validate($data, 'Article');
            
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if ($this->article_model->allowField(true)->save($data, $id) !== false) {
                    //文章标签关联
                    $this->linkArticleLabel($data,$id);
                    
                    //文章专题关联
                    $this->linkArticleSubject($data,$id);
                    
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除文章
     * @param int   $id
     * @param array $ids
     */
    public function delete($id = 0, $ids = []) {
        $id = $ids ? $ids : $id;
        if ($id) {
            if ($this->article_model->destroy($id)) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('请选择需要删除的文章');
        }
    }
    
    /**
     * 删除医院文章
     * @param int   $id
     * @param array $ids
     */
    public function delete2($id = 0, $ids = []) {
        $id = $ids ? $ids : $id;
        if ($id) {
            if (Db::name('Article2')->delete($id)) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('请选择需要删除的文章');
        }
    }
    
    /**
     * 添加医院文章
     */
    public function addHospital () {
        
        if ($this->request->isPost()) {
            $data = $this->request->post();
            
            //处理附近景色
            $data = $this->dealJs($data);
            $validate_result = $this->validate($data, 'Article2');

            $data['publish_time'] = time();
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $status = Db::name('Article2')->insert($data);
                if($status)
                    $this->success ('添加成功');
                else
                    $this->error ('添加失败');
            }
        }
        
        return $this->fetch();
    }
    
    /**
     * 编辑医院文章
     */
    public function saveHospital () {
        
        if ($this->request->isPost()) {
            $data = $this->request->post();
            
            //处理附近景色
            $data = $this->dealJs($data);
            $validate_result = $this->validate($data, 'Article2.edit');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $status = Db::name('Article2')->update($data);
                if($status)
                    $this->success ('修改成功');
                else
                    $this->error ('修改失败');
            }
            
        }
        
        $id = input('param.id');
        $article = Db::name('Article2')->find($id);        
        $this->assign('article',$article);
        return $this->fetch();
    }
    
    /**
     * 处理景色
     */
    public function dealJs($data) {
        $images = array();
        if ($data['scenery'] && is_array($data['scenery'])) {
            foreach ($data['scenery']['img'] as $k => $v) {
                $images[$k]['img'] = $v;
            }
            foreach ($data['scenery']['title'] as $k => $v) {
                $images[$k]['title'] = $v;
            }
            foreach ($data['scenery']['intor'] as $k => $v) {
                $images[$k]['intor'] = $v;
            }
        }
        $data['scenery'] = serialize($images);
        return $data;
    }
    

    /**
     * 文章审核状态切换
     * @param array  $ids
     * @param string $type 操作类型
     */
    public function toggle($ids = [], $type = '') {
        $data = [];
        $status = $type == 'audit' ? 1 : 0;

        if (!empty($ids)) {
            foreach ($ids as $value) {
                $data[] = ['id' => $value, 'status' => $status];
            }
            
            
            if ($this->article_model->saveAll($data)) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        } else {
            $this->error('请选择需要操作的文章');
        }
    }

    /**
     * 文章标签关联
     * @param type $data
     * @param type $article_id
     */
    public function linkArticleLabel($data,$article_id) {
        if (($data['labels'] && $data['pingying'])) {
            $labels = explode(',', str_replace('，', ',', $data['labels']));
            $pingying = explode(',', str_replace('，', ',', $data['pingying']));

            $result = array();
            foreach ($labels as $k => $v) {
                $result['label_name'] = $v;
                $result['label_fist'] = ucfirst(substr($pingying[$k], 0, 1));
                $result['pingying'] = $pingying[$k];
                $result['sort'] = 0;

                //查找标签
                $name = Db::name('Label')->where(['label_name'=>$v])->find();
                                
                //如果标签不存在
                if(!$name){
                    //插入标签表
                    Db::name('Label')->insert($result);

                    //获取id
                    $id = Db::name('Label')->getLastInsID();

                    //插入文章关联表
                    $r[] = array(
                        'article_id'=>$article_id,
                        'label_id'=>$id,
                    );
                }else{
                    //插入文章关联表
                    $r[] = array(
                        'article_id'=>$article_id,
                        'label_id'=>$name['id']
                    );
                }
            }
            
            //删除该文章全部的标签数据 统一再加一遍
            Db::name('ArticleLabel')->where(['article_id'=>$article_id])->delete();
            
            if(!Db::name('ArticleLabel')->insertAll($r)){
                $this->error('关联数据添加失败！');
            }
        }
    }
    
    /**
     * 文章专题关联
     */
    public function linkArticleSubject ($data,$article_id) {
        //如果指定要加专题的话
            if(isset($data['subject'])){
                foreach ($data['subject'] as $k=>$v){
                    //找出该专题的信息
                    $subject_info = Db::name('Subject')->where(['id'=>$v])->find();

                    //把该文章绑定到专题的article_ids
                    if($subject_info['article_ids']){
                        //如果该文章不在该专题下
                        if(strpos($subject_info['article_ids'],$article_id) === false){
                            $status = Db::name('Subject')->where(['id'=>$v])->update(['article_ids'=>  $subject_info['article_ids'].$article_id.',']);
                        }else{
                            $status = 1;
                        }
                    }else{
                        $status = Db::name('Subject')->where(['id'=>$v])->update(['article_ids'=>$article_id.',']);
                    }
                    
                    if($status === false){
                        $this->error('添加到专题失败！');
                    }
                }
            }
    }
    
    
    
    
    /**
    * 获取文章第一张图片做为缩略图
    * @param $content
    * @return bool|string
    */
    public function thumb($content){
       $content = stripslashes($content);
       if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
           $str = $matches[3][0];
           $str = substr($str, 6);
           if (preg_match('/upload/', $str)) {
               return $str;
           }
       }
       return '';
   }
   
   /**
     * 获取关键字所有文章
     */
    public function getSubjectByKey () {
        $key = input('param.key');
        $where = 1;
        if($key)
            $where .= ' and name like "%'.$key.'%"';
        
        //获取带关键字的文章
        $subject_list = Db::name('Subject')->field('id,name')->where($where)->select();
        
        $subject_list ? die(handleResult(1, '',$subject_list)) : die(handleResult(0, '该关键词没有相关专题！'));
    }

}
